<template>
  <el-dialog
    title="批量导入"
    :visible.sync="visible"
    width="680px"
    :before-close="handleClose"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <div class="import-wrap" v-if="visible">
      <div class="import-tips">
        <p class="tips">
          <i class="el-icon-warning-outline danger"></i>特别提示
        </p>
        <p class="blue">
          导入过程中如发现身份证号码相同的资源，后面解析的数据不会覆盖之前已解析的数据
        </p>
      </div>
      <el-form :model="form" ref="form" label-width="90px" class="radio-wrap">
        <el-form-item
          label="导入类型:"
          prop="confId"
          :rules="[
            { required: true, message: '导入类型不能为空', trigger: 'change' }
          ]"
        >
          <el-radio-group v-model="form.confId" @change="handleFileTypeChange">
            <el-radio
              v-for="item in typeList"
              :label="item.confId"
              :key="item.confId"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template v-if="form.confId">
        <div class="import-cont is-flex">
          <img class="icon" src="../../../assets/images/download.png" />
          <div>
            <a :href="templateUrl">
              <el-button type="text">下载模板</el-button>
            </a>
            <div class="sub-title">
              请按照数据模板的格式准备导入数据，模板中的表头名称不可更改，表头行不能删除
            </div>
          </div>
        </div>
        <div class="import-cont is-flex">
          <img class="icon" src="../../../assets/images/upload.png" />
          <div>
            <el-upload
              ref="upload"
              action="/"
              accept=".xls, .xlsx"
              :limit="1"
              :on-change="importExcel"
              :on-exceed="handleExceed"
              :auto-upload="false"
            >
              <el-button slot="trigger" type="text">上传文件</el-button>
            </el-upload>
            <div class="sub-title">
              文件后缀名必须为xls 或xlsx
              （即Excel格式），文件大小不得大于5M，最多支持导入
              <span class="num">4000</span> 条数据
            </div>
          </div>
        </div>
      </template>
    </div>
    <span class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
    </span>
    <LoadingProgress
      :loading="modalLoading"
      :text="loadingText"
      :percentage="percentage"
    ></LoadingProgress>
  </el-dialog>
</template>

<script>
import axios from 'axios';
import { apiJava } from '@/api/root';
import { offlineGetResult } from '@/api/index';
import LoadingProgress from '@/components/LoadingProgress';
export default {
  components: {
    LoadingProgress
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    cardType: {
      type: [String, Number],
      default: ''
    },
    typeList: {
      type: Array,
      default: () => []
    },
    configObj: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      form: {
        confId: ''
      },
      templateUrl: '',
      fileList: [],
      retryCount: 0,
      MAX_RETRY_TIMES: 1000,
      timer: null,
      redisId: '',
      percentage: 0,
      modalLoading: false,
      loadingText: ''
    };
  },
  methods: {
    handleFileTypeChange(val) {
      const temp = this.typeList.find((item) => item.confId === val);
      this.templateUrl = temp.templateUrl;
    },
    handleClose() {
      this.fileList = [];
      this.$emit('update:visible', false);
    },
    handleConfirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.fileList || (this.fileList && !this.fileList.length)) {
            this.$alert('请先上传文件！');
            return false;
          }
          if (
            this.fileList.length &&
            this.fileList[0].size > 1024 * 1024 * 10
          ) {
            this.$message.warning('导入文件请勿超过10MB！');
            return false;
          }

          this.loadingText = `正在导入数据，已完成${'' + this.percentage}%`;
          this.modalLoading = true;

          let formData = new FormData();
          formData.append('file', this.fileList[0].raw);
          formData.append('cardType', this.cardType);
          formData.append('confId', this.form.confId);
          formData.append('setCode', this.configObj.setCode);
          axios({
            method: 'post',
            url: `${apiJava}/api-career/zt/offline/batch/import`,
            data: formData,
            headers: {
              'Content-Type': 'application/x-www-form-urlencode',
              Authorization: sessionStorage.getItem('loginInfo')
                ? JSON.parse(sessionStorage.getItem('loginInfo')).token
                : ''
            }
          })
            .then((res) => {
              if (res.code == 200) {
                this.redisId = res.data;
                setTimeout(() => {
                  this.startRequest();
                }, 5000);
              } else {
                this.$message.error(res.data.status_desc);
              }
            })
            .catch((err) => {
              this.modalLoading = false;
              this.percentage = 0;
              this.$message.error('导入失败，请重试！');
            });
        } else {
          return false;
        }
      });
    },
    offlineGetResultFn() {
      this.retryCount++;
      offlineGetResult({ redisId: this.redisId })
        .then((res) => {
          if (res.code == 200) {
            if (res.data.code == 1) {
              this.endRequest();
              this.$message.success('数据导入成功');
              this.$emit('refresh');
              this.handleClose();
            } else if (res.data.code == 2) {
              // 导入失败
              this.endRequest();
              this.$message.error('此日期范围无数据或者服务器繁忙，请稍后再试');
            } else {
              // 正在导入
              this.percentage = +res.data.percent;
              this.loadingText = `正在导入数据，已完成${'' + this.percentage}%`;
            }
          } else {
            this.$message.error(res.status_desc);
            this.endRequest();
          }
        })
        .catch((err) => {
          this.$message.error(err);
          this.endRequest();
        });
    },
    startRequest() {
      this.timer = setInterval(() => {
        if (this.retryCount < this.MAX_RETRY_TIMES) {
          this.offlineGetResultFn();
        } else {
          this.$message.error('超过最大的重试次数，请稍后重试！');
          clearInterval(this.timer);
          this.modalLoading = false;
          this.percentage = 0;
        }
      }, 5000);
    },
    endRequest() {
      clearInterval(this.timer);
      this.timer = null;
      this.modalLoading = false;
      this.percentage = 0;
    },
    importExcel(file, fileList) {
      let list = fileList;
      if (this.fileList.lenth > 0) {
        this.$message.warning(
          '只能上传一个文件，若需更新，请先将下方选项移除！'
        );
        return false;
      }
      const types = file.name.split('.')[1];
      const fileType = ['xlsx', 'xls'].some((item) => item === types);
      if (!fileType) {
        this.$message.warning('格式错误！请重新选择！');
        this.fileList = list.splice(0);
        return false;
      }
      if (file.size > 1024 * 1024 * 10) {
        this.$message.warning('导入文件请勿超过10MB！');
        this.fileList = list;
        return false;
      }
      this.fileList = list;
    },
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$message.warning('只能上传一个文件，若需更新，请先将下方选项移除！');
    }
  }
};
</script>

<style lang="scss" scoped>
.import-wrap {
  color: #9c9ca1;
  padding: 24px;
  border-bottom: 1px solid #d2d5e1;
  .radio-wrap {
    padding: 12px 0;
  }
  .import-cont {
    padding: 10px;
    border: 1px solid #d2d5e1;
    border-radius: 6px;
    margin-bottom: 12px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  ::v-deep .el-form-item__label {
    font-size: 15px;
    font-weight: 600;
    color: #333;
  }
}
.icon {
  margin-right: 24px;
}
.sub-title {
  margin: 0 0 8px 0;
  .num {
    color: #333;
    font-weight: 600;
  }
}
.import-tips {
  background-color: #f5f9ff;
  border-radius: 2px;
  padding: 12px 24px;
  color: #b8b9be;
  margin: -24px -24px 0px -24px;
  .tips {
    color: #ec4343;
  }
  .danger {
    color: #ec4343;
    margin-right: 8px;
  }
  .blue {
    padding-top: 8px;
    color: #86868f;
    &.step-2 {
      padding: 0;
    }
  }
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 24px;
}
.is-flex {
  display: flex;
  align-items: center;
}
::v-deep .el-dialog__body {
  padding: 0;
}
</style>
